﻿<%@ WebHandler Language="C#" Class="Apollo.Website.JSONEntity" %>

using System;
using System.Web;
using Apollo;
using Apollo.Core;
using System.Linq;

namespace Apollo.Website
{
    public class JSONEntity : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            
            int viewId = 0;
            int objectId = 0;
            if (int.TryParse(context.Request["ViewId"], out viewId) && int.TryParse(context.Request["ObjectId"], out objectId))
            {
                EntityView ev = Apollo.Application.Meta<EntityView>()
                            .SingleOrDefault<EntityView>(e => e.Id == viewId);

                if (ev != null)
                {
                    object obj = Apollo.Application.CurrentSession.Get(ev.Entity.MappedClass, objectId);

                    Projection idProjection = new Projection(ev.Entity.IdentifierProperty, ev.Entity.MappedClass);
                    Projection displayProjection = new Projection(ev.Entity.DisplayProperty, ev.Entity.MappedClass);

                    context.Response.Write(@"
                { 
                    ""Id"": """ + idProjection.Apply(obj).ToString() + @""", 
                    ""DisplayName"": """ + displayProjection.Apply(obj).ToString() + @"""
                } 
                ");
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}